﻿using System;
using System.Collections.Generic;

using System.Text;
using System.IO;

namespace SQLDeployActions
{
    public class DeployVerification
    {
        private static void CheckArgs(string[] args)
        {

            if (!(args.Length == 4 || args.Length == 2))
            {
                throw new ArgumentException(DeployConstants.MSG_INSUFFICIENT_INFO
                                            + System.Environment.NewLine
                                            + DeployConstants.MSG_USAGE
                                            );
            }
            //Args 3 and 4 are Uname and PWD. If they are not provided, then use trusted connection.
            DeployConstants.IsTrustedConnection = (args.Length == 2);
        }

        private static void CheckSequenceFile()
        {
            if (!File.Exists(DeployConstants.SQLSequenceFile))
            {
                throw new FileNotFoundException(DeployConstants.MSG_NO_SEQUENCE_FILE);
            }
            FileInfo sequenceFileinfo = new FileInfo(DeployConstants.SQLSequenceFile);
            {
                if (sequenceFileinfo.Length == 0)
                {
                    throw new DeployException(DeployConstants.MSG_SEQUENCE_FILE_EMPTY);
                }
            }
        }

        private static void CheckConnection()
        {
            string msg = string.Empty;
            StringBuilder SQLCMD_Command = new StringBuilder();
            SQLCMD_Command.Append(" -Q \"select 'connected'\" ");
            SQLCMD_Command.Append(DeployConstants.SERVER_OPTION + DeployConstants.ServerName);
            SQLCMD_Command.Append(DeployConstants.DB_OPTION + DeployConstants.DBName);
            DeployActionExecute.SetSecurityOption(SQLCMD_Command);
            msg = DeployActionExecute.ExecuteProcess(DeployConstants.SQLCMD_EXE, SQLCMD_Command.ToString());
            if (msg.Contains("connected"))
                Console.WriteLine(DeployConstants.MSG_CONNECTED);
            else
            {
                throw new ApplicationException(msg + DeployConstants.MSG_ABORT);
            }
        }

        public static void PreDeployVerification(string[] args)
        {
            CheckArgs(args);
            DeployActions.LoadAppSettings(args);
            CheckSequenceFile();
            CheckConnection();
        }
    }
}
